const express = require("express");
const db = require("../config");

const storeRouter = express.Router();
/* 查询所有店铺 */
storeRouter.get("/getAllStore", (req, res) => { 
    const sql ="select * from db_store";
    db.query(sql,(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.length == 0) return res.fail("查询所有店铺失败，请重试");
        res.send({
            status:0,
            message:"查询所有店铺成功",
            data:result
        })
    })
 });
/* 添加店铺 */
storeRouter.post("/addStore", (req, res) => { 
    const {userId,storeName,logo,cover,description} = req.body;
    const sql ="insert into db_store(userId,storeName,logo,cover,description) values (?,?,?,?,?)";
    db.query(sql,[userId,storeName,logo,cover,description],(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.affectedRows!==1) return res.fail("注册店铺失败，请重试");
        res.send({
            status:0,
            message:"注册店铺成功"
        })
    })

 });
/* 更新店铺指定信息 */
storeRouter.post("/updateStore", (req, res) => { 
    const {id,storeName,logo,cover,description} = req.body;
    const sql ="update db_store set storeName=?,logo=?,cover=?,description=? where id=?";
    db.query(sql,[storeName,logo,cover,description,id],(err,result)=>{
        console.log(result);
        
        if(err) return res.fail(err.message);
        if(result.affectedRows!==1) return res.fail("更新店铺信息失败，请重试");
        res.send({
            status:0,
            message:"更新店铺信息成功"
        })
    })
 });
/* 删除店铺 */
storeRouter.post("/delStore", (req, res) => { 
    const sql ="update db_store set status=0 where id =?";
    db.query(sql,req.body.id,(err,result)=>{
        if(err) return res.fail(err.message);
        if(result.affectedRows!==1) return res.fail("删除店铺失败，请重试");
        res.send({
            status:0,
            message:"删除店铺成功"
        })
    })
 });

module.exports = { storeRouter };